<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { getHumidityDataApi } from '@/api/report';
import { ElMessage } from 'element-plus';

//数据源
const timeList = ref([]);
const humidityList = ref([]);
const chartRef = ref();
const time = ref("day");

let myChart = null;

onMounted(async () => {
  queryData();
})

//查询数据
const queryData = async () => { 
  const result = await getHumidityDataApi(time.value);
  if (result.code) { 
    timeList.value = result.data.timeList;
    humidityList.value = result.data.dataList;
    // 使用 nextTick 确保 DOM 更新后再初始化图表
    await nextTick();
    initChart();
  } else {
    ElMessage.error("获取湿度数据失败");
  }
}

const initChart = () => {
  if (chartRef.value) {
    // 如果图表已经存在，先销毁
    if (myChart) {
      myChart.dispose();
    }
    // 初始化图表
    myChart = echarts.init(chartRef.value);
    updateChart();
    
    // 监听窗口大小变化，自适应图表
    window.addEventListener('resize', () => {
      if (myChart) {
        myChart.resize();
      }
    });
  }
}

const updateChart = () => {
  if (myChart) {
    const option = {
      title: {
        text: '湿度历史数据',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: timeList.value,
        axisLabel: {
          // X轴标签优化显示
          interval: 0, // 显示所有标签
          rotate: 45,  // 标签旋转45度
        }
      },
      yAxis: {
        type: 'value',
        name: '湿度 (%)'
      },
      dataZoom: [
        {
          type: 'inside',
          start: 0,
          end: 100
        },
      ],
      series: [
        {
          name: '湿度',
          data: humidityList.value,
          type: 'line',
          smooth: true,
          markLine: {
            symbol: ['none', 'none'], // 移除标记线两端的箭头
          }
        }
      ]
    };
    
    myChart.setOption(option);
  }
}

// 当数据变化时更新图表
watch([timeList, humidityList], () => {
  updateChart();
});

watch(time, () => { 
  queryData();
})

const selectContent = [
  {
    value: 'day',
    label: '24小时内湿度数据',
  },
  {
    value: 'week',
    label: '最近7天湿度数据',
  },
  {
    value: 'month',
    label: '最近30天湿度数据',
  },
  {
    value: 'year',
    label: '最近1年湿度数据',
  },
]
</script>

<template>
  <div>
    <el-tree-select
      v-model="time"
      :data="selectContent"
      :render-after-expand="false"
      style="width: 180px"
    />
  </div>

  <div class="chart-container">
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<style scoped>
.chart-container {
  padding: 20px;
}

.chart {
  width: 100%;
  height: 500px;
}
</style>